package xonmp.notepaddemo.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class NotepadDbAdapter {
	
	public static final String KEY_TITLE = "title";
	public static final String KEY_BODY = "body";
	public static final String KEY_ROWID = "_id";
	
	private static final String TAG = "NotepadDbAdapter";
	private NotepadDbHelper mDbHelper;
	private SQLiteDatabase mDb;
	
	private final Context mContext;
	
	public NotepadDbAdapter(Context context)
	{
		mContext = context;
	}
	
	public NotepadDbAdapter open() throws SQLException
	{
		mDbHelper = new NotepadDbHelper(mContext);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}
	
	public void close()
	{
		mDbHelper.close();
	}
	
	public long createNote(String title, String body)
	{
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_TITLE, title);
		initialValues.put(KEY_BODY, body);
		
		return mDb.insert(NotepadDbHelper.DATABASE_TABLE, null, initialValues);
	}
	
	public boolean deleteNote(long rowId)
	{
		return mDb.delete(NotepadDbHelper.DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}
	
	public Cursor fetchAllNotes()
	{
		return mDb.query(NotepadDbHelper.DATABASE_TABLE, 
				new String[] {KEY_ROWID, KEY_TITLE, KEY_BODY}, 
				null, null, null, null, null);
	}
	
	public Cursor fetchNote(long rowId) throws SQLException
	{
		Cursor mCursor = mDb.query(NotepadDbHelper.DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_BODY}, 
				KEY_ROWID + "=" + rowId, null, null, null, null);
		if (mCursor != null)
		{
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	public boolean updateNote(long rowId, String title, String body)
	{
		ContentValues args = new ContentValues();
		args.put(KEY_TITLE, title);
		args.put(KEY_BODY, body);
		
		return mDb.update(NotepadDbHelper.DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
	}
}
